import logging
import os
import threading
import time

from myapp.third.nacos import client


class Config:
    def __init__(self, key, group, fmt='json', refresh_interval=300):
        self.key = key
        self.group = group
        self.fmt = fmt
        self.refresh_interval = refresh_interval
        self._config = None
        self.last_update_time = 0
        self.lock = threading.Lock()

    def _refresh(self):
        # 每隔refresh_interval秒 刷新一次配置
        now = time.time()
        if now - self.last_update_time < self.refresh_interval:
            return

        with self.lock:
            now = time.time()
            if now - self.last_update_time < self.refresh_interval:
                return

            logging.info(f'refresh config, pid:{os.getpid()}, key:{self.key}')
            self._config = client.get_config(self.key, self.group, fmt=self.fmt)
            self.last_update_time = now

    def get(self, key, default=None):
        self._refresh()
        if self._config is None:
            return default
        return self._config.get(key, default)

    def __getitem__(self, item):
        self._refresh()
        if self._config is None:
            return None
        return self._config[item]

    def to_dict(self):
        self._refresh()
        return self._config

    def __str__(self):
        self._refresh()
        return str(self._config)
